﻿using AutoMapper;
using B.S.GridManage.Api.Write.Application.Command.DutyGrid;
using B.S.GridManage.Domain.Entities;
using B.S.GridManage.ErrorCode;
using B.S.GridManage.Infrastructure.Interface;
using MediatR;
using System.Transactions;
using Yitter.IdGenerator;

namespace B.S.GridManage.Api.Write.Application.Handler.DutyGrid
{
    public class CreateDutyHandler : IRequestHandler<CreateDutyCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<DutyGridModel> dutyRepo;
        private readonly IMapper mapper;
        private readonly ILogger<CreateDutyHandler> logger;

        public CreateDutyHandler(IBaseRepository<DutyGridModel> dutyRepo,IMapper mapper,ILogger<CreateDutyHandler> logger)
        {
            this.dutyRepo = dutyRepo;
            this.mapper = mapper;
            this.logger = logger;
        }

       

        public async Task<ApiResult<int>> Handle(CreateDutyCommand request, CancellationToken cancellationToken)
        {

            ApiResult<int> res = new ApiResult<int>();
            //唯一性校验
            var dutyEntity = dutyRepo.GetAll().Where(x => x.DutyGridName == request.DutyGridName).FirstOrDefault();
            if (dutyEntity!=null)
            {
                res.Msg = "责任网格" + request.DutyGridName + "已经存在";
                res.Code = ApiEnum.Failed;
                return  res;
            }

            //唯一性校验
              dutyEntity = dutyRepo.GetAll().Where(x => x.DutyGridCode == request.DutyGridCode).FirstOrDefault();
            if (dutyEntity != null)
            {
                res.Msg = "责任网格编号:" + request.DutyGridCode + "已经存在";
                res.Code = ApiEnum.Failed;
                return  res;
            }

            var model = mapper.Map<DutyGridModel>(request);
            model.Id = YitIdHelper.NextId();

            var r = 0;
            //分布式事务
            using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    r = await dutyRepo.CreateAsync(model);//数据库操作1
                  //数据库操作2
                  //数据库操作3
                  //数据库操作4
                  //数据库操作5


                    tran.Complete();

                }
                catch (Exception e)
                {
                    
                    //分布式事务,自动回滚
                    //记录事务回滚日志
                    logger.LogError("发生错误,添加责任网格已回滚:"+e.Message);

                }
            }

            if (r >0) {
                res.Msg = "责任网格编号添加成功";
                res.Code = ApiEnum.Success;
                res.Data = r;
                 
            }else
            {
                res.Msg = "责任网格编号添加失败";
                res.Code = ApiEnum.Failed;
                res.Data = r;
               
            }
            return res;
        }
    }
}
